﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using KeepAccounts.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace KeepAccounts.Api.Extensions
{
    public class GlobalExceptions
    {
        private readonly RequestDelegate requestDelegate;

        public GlobalExceptions(RequestDelegate rd)
        {
            requestDelegate = rd;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await requestDelegate(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static async Task HandleExceptionAsync(HttpContext context, Exception e)
        {
            if (e == null) return;

            LogHelper.ErrorLog(e.Source, e);

            await WriteExceptionAsync(context, e).ConfigureAwait(false);
        }

        private static async Task WriteExceptionAsync(HttpContext context, Exception e)
        {
            if (e is UnauthorizedAccessException)
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            else if (e is Models.ApiException)
                context.Response.StatusCode = (int)HttpStatusCode.OK;
            else if (e is Exception) {
                LogHelper.ErrorLog(e.Source, e);
                context.Response.StatusCode = (int)HttpStatusCode.OK;
            }
            context.Response.ContentType = "application/json";
     
            //bool isAjaxCall = context.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            //if (isAjaxCall)
            //{
            await context.Response.WriteAsync(
                JsonConvert.SerializeObject(Models.ResponseModel.Error(e.GetBaseException().Message), Formatting.Indented, new JsonSerializerSettings
                {
                    ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver()
                })).ConfigureAwait(false);
            //}
            //else
            //{
            //    context.Response.Redirect("/Home/Error");
            //}
        }
    }
}
